package org.common.utils.rpc.net.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.common.utils.net.netty.core.NettyHandler;
import org.common.utils.rpc.core.RpcRequestPool;
import org.common.utils.rpc.entity.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executor;

/**
 * RPC客户端处理器
 * @author zhouzhibing
 * @date 2025/11/16 17:53
 */
@ChannelHandler.Sharable
public class RpcClientNettyHandler extends NettyHandler {

    private static final Logger log = LoggerFactory.getLogger(RpcClientNettyHandler.class);
    /**
     * 消息池
     */
    private final RpcRequestPool requestPool;
    /**
     * 执行器
     */
    private final Executor executor;

    public RpcClientNettyHandler(RpcRequestPool requestPool , Executor executor) {
        this.requestPool = requestPool;
        this.executor = executor;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            RpcResponse response = (RpcResponse)msg;
            if(executor == null) {
                requestPool.addResponse(response);
            } else {
                executor.execute(() -> requestPool.addResponse(response));
            }
        } catch (Exception e) {
            log.error("channelRead error " , e);
        }
    }
}
